package seller

import (
    "time"
	"strconv"
	"dhfshop/controllers/base"
	"dhfshop/models/seller"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type PrintController struct {
	base.BaseController
}

// 查询打印模板
func (this *PrintController) List() {
	curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	companyId :=int64(this.Ctx.Input.GetData("curCompanyId").(int))
	//curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	query,_, fields, order_by, offset, limit, err := this.GetQueryPara()
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if curRoleId == 1 {
	    
	}else if curRoleId == 2 {
	    query["partner_id"] = strconv.FormatInt(companyId, 10)
	}else{
	
	}
	l, cnt, err := seller.GetAllPrints(query, fields, order_by, offset, limit)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount int64        `json:"total_count"`
		Prints     []*seller.Print `json:"prints"`
	}{TotalCount: cnt, Prints: l}
	this.Data["json"] = r
	this.ServeJSON()
}

// 添加打印模板
func (this *PrintController) Add() {
	var v seller.Print
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.TypeId, "type_id")
	valid.Required(v.Content, "content")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	id, err := seller.AddPrint(&v)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	v.PrintId = int64(id)
	this.Data["json"] = v
	this.ServeJSON()
}

// 更新一个打印模板
func (this *PrintController) Update() {
	var v seller.Print
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.PrintId, "print_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"print_id","partner_id"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
		err := seller.UpdatePrint(&v, updateFields...)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		PrintId  int64     `json:"print_id"`
		Modified time.Time `json:"modified"`
	}{PrintId: v.PrintId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

// 删除一个打印模板
func (this *PrintController) Delete() {
	var v seller.Print
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.PrintId, "print_id")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	err := seller.DeletePrint(v.PrintId)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		PrintId  int64     `json:"print_id"`
		Modified time.Time `json:"modified"`
	}{PrintId: v.PrintId, Modified: time.Now().UTC()}
	this.Data["json"] = r
	this.ServeJSON()
}
